import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:family_app/src/features/finance/models/transaction_model.dart';
import 'package:family_app/src/features/finance/providers/finance_provider.dart';
import 'package:family_app/src/features/finance/widgets/transaction_list_item.dart';
import 'package:family_app/src/theme/app_theme.dart';

/// 分类统计 Tab
/// 左侧显示分类列表，右侧显示所选分类的交易明细
/// 支持按年份筛选
class FinanceCategoryTab extends ConsumerStatefulWidget {
  const FinanceCategoryTab({Key? key}) : super(key: key);

  @override
  ConsumerState<FinanceCategoryTab> createState() => _FinanceCategoryTabState();
}

class _FinanceCategoryTabState extends ConsumerState<FinanceCategoryTab> {
  // 当前年份
  late int _currentYear;
  // 选择的年份
  late int _selectedYear;
  // 选择的分类
  String? _selectedCategory;

  @override
  void initState() {
    super.initState();
    final now = DateTime.now();
    _currentYear = now.year;
    _selectedYear = _currentYear;
  }

  @override
  Widget build(BuildContext context) {
    // 获取所有分类
    final categoriesAsync = ref.watch(allCategoriesProvider);

    return categoriesAsync.when(
      data: (categories) {
        // 确保有选中的分类
        if (_selectedCategory == null && categories.isNotEmpty) {
          _selectedCategory = categories.first;
        }

        return Column(
          children: [
            // 年份选择器
            _buildYearSelector(),
            
            // 分类列表和交易明细
            Expanded(
              child: Row(
                children: [
                  // 左侧分类列表
                  Container(
                    width: 120.w,
                    decoration: BoxDecoration(
                      color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
                      border: Border(
                        right: BorderSide(
                          color: Colors.grey.withOpacity(0.2),
                          width: 1,
                        ),
                      ),
                    ),
                    child: _buildCategoryList(categories),
                  ),
                  
                  // 右侧交易明细
                  Expanded(
                    child: _selectedCategory != null
                        ? _buildCategoryTransactions(_selectedCategory!)
                        : const Center(child: Text('请选择一个分类')),
                  ),
                ],
              ),
            ),
          ],
        );
      },
      loading: () => const Center(child: CircularProgressIndicator()),
      error: (error, _) => Center(
        child: Text('加载失败: $error', style: TextStyle(color: Colors.red)),
      ),
    );
  }

  /// 构建年份选择器
  Widget _buildYearSelector() {
    // 生成最近5年的年份列表
    final years = List.generate(5, (index) => _currentYear - index);

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      color: Theme.of(context).colorScheme.surfaceVariant.withOpacity(0.3),
      child: Row(
        children: [
          Text(
            '选择年份：',
            style: TextStyle(fontSize: 16.sp, fontWeight: FontWeight.bold),
          ),
          SizedBox(width: 8.w),
          DropdownButton<int>(
            value: _selectedYear,
            items: years.map((year) {
              return DropdownMenuItem<int>(
                value: year,
                child: Text('$year 年'),
              );
            }).toList(),
            onChanged: (value) {
              if (value != null) {
                setState(() {
                  _selectedYear = value;
                });
              }
            },
            underline: Container(),
            style: TextStyle(fontSize: 16.sp, color: AppTheme.primaryColor, fontWeight: FontWeight.bold),
          ),
        ],
      ),
    );
  }

  /// 构建分类列表
  Widget _buildCategoryList(List<String> categories) {
    return ListView.builder(
      itemCount: categories.length,
      itemBuilder: (context, index) {
        final category = categories[index];
        final isSelected = category == _selectedCategory;

        return ListTile(
          title: Text(
            category,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: isSelected ? FontWeight.bold : FontWeight.normal,
              color: isSelected ? AppTheme.primaryColor : null,
            ),
          ),
          selected: isSelected,
          selectedTileColor: Theme.of(context).colorScheme.primaryContainer.withOpacity(0.3),
          onTap: () {
            setState(() {
              _selectedCategory = category;
            });
          },
        );
      },
    );
  }

  /// 构建分类交易明细
  Widget _buildCategoryTransactions(String category) {
    // 创建年份的第一天和最后一天，用于查询该年交易
    final firstDayOfYear = DateTime(_selectedYear, 1, 1);
    final lastDayOfYear = DateTime(_selectedYear, 12, 31, 23, 59, 59);
    final dateRange = (firstDayOfYear, lastDayOfYear);

    // 获取该分类在选定年份的交易数据
    final categoryTransactionsAsync = ref.watch(
      categoryTransactionsProvider((dateRange, category)),
    );

    return Column(
      children: [
        // 分类标题
        Padding(
          padding: EdgeInsets.all(16.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '$category - ${_selectedYear}年',
                style: TextStyle(fontSize: 18.sp, fontWeight: FontWeight.bold),
              ),
              // 分类统计信息
              categoryTransactionsAsync.whenData((transactions) {
                final total = transactions.fold<int>(
                  0,
                  (sum, tx) => tx.type == TransactionType.expense ? sum + tx.amount : sum,
                );
                return Text(
                  '总支出: ¥${total.toStringAsFixed(2)}',
                  style: TextStyle(fontSize: 16.sp, color: Colors.red),
                );
              }).value ?? const SizedBox(),
            ],
          ),
        ),

        // 交易列表
        Expanded(
          child: categoryTransactionsAsync.when(
            data: (transactions) => _buildTransactionList(transactions),
            loading: () => const Center(child: CircularProgressIndicator()),
            error: (error, _) => Center(
              child: Text('加载失败: $error', style: TextStyle(color: Colors.red)),
            ),
          ),
        ),
      ],
    );
  }

  /// 构建交易列表
  Widget _buildTransactionList(List<TransactionModel> transactions) {
    if (transactions.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.search_off, size: 64.r, color: Colors.grey),
            SizedBox(height: 16.h),
            Text(
              '没有找到相关交易记录',
              style: TextStyle(fontSize: 16.sp, color: Colors.grey),
            ),
          ],
        ),
      );
    }

    // 按日期降序排序
    final sortedTransactions = List<TransactionModel>.from(transactions)
      ..sort((a, b) => b.transactionDate.compareTo(a.transactionDate));

    return ListView.builder(
      padding: EdgeInsets.symmetric(horizontal: 16.w),
      itemCount: sortedTransactions.length,
      itemBuilder: (context, index) {
        final transaction = sortedTransactions[index];
        return TransactionListItem(
          transaction: transaction,
          onTap: () {
            // 显示编辑交易对话框
            // 这里需要调用父组件的方法，暂时留空
          },
          onDelete: () {
            // 显示删除交易确认对话框
            // 这里需要调用父组件的方法，暂时留空
          },
        );
      },
    );
  }
}
